/*
 * Copyright 2019 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

import {customer, security} from "@mall/api-services";
import * as _ from "lodash";
import * as  qs from "qs";
import * as React from "react";
import {useEffect, useState} from "react";
import {RouteComponentProps, withRouter} from "react-router";
import Search from "../components/search";
import Icon from "../icon";
import "./index.scss";
import SearchResult from "./search-result";


interface SearchRecommendationProps {
    name?: string;
    onSelectText: (text: string) => void
}

function SearchRecommendation({name, onSelectText}: SearchRecommendationProps) {

    const [searchTerms, setSearchTerms] = useState([] as customer.SearchTerm[]);

    useEffect(() => {
        const customerId = security.SecurityUserHolder.getUserId();
        customer.SearchTermServiceV1
            .getSearchTerms(customerId)
            .then(terms => {
                setSearchTerms(terms);
            });

    }, [name]);

    return (
        <>
            <div className="search-history">
                <div className="search-history-title">
                    <span>搜索历史</span>
                    <Icon type="delete" size="xxs"/>
                </div>
                <div className="search-history-content">
                    {_.map(searchTerms, term => (
                        <span
                            key={term.text}
                            className="search-history-label"
                            onClick={() => onSelectText(term.text)}>{term.text}</span>
                    ))}
                </div>
            </div>
        </>
    );
}

interface SearchKeywordListProps {

}

export class SearchKeywordList extends React.Component<SearchKeywordListProps> {

    public render() {
        return (
            <div className="search-keyword-list">
                <div className="search-keyword-item">小米</div>
                <div className="search-keyword-item">小米手机</div>
                <div className="search-keyword-item">小米笔记本</div>
            </div>
        );
    }
}

interface SearchParams {
    name?: string;
}

interface SearchProps extends RouteComponentProps {

}

function parseSearchParams(search: string): SearchParams {
    const trimSearch = search.trim();
    return _.isEmpty(trimSearch) ? {} : qs.parse(trimSearch.substring(1));
}

function addSearchTerm(text?: string) {
    const customerId = security.SecurityUserHolder.getUserId();
    const trimText = _.trim(text);
    if (text !== undefined && !_.isEmpty(trimText)) {
        customer.SearchTermServiceV1
            .addSearchTerm(customerId, trimText)
            .then(() => console.log('Add a search text.'));
    }
}

function SearchComponent(props: SearchProps) {
    const {history} = props;
    const {name} = parseSearchParams(history.location.search);
    const [searchText, setSearchText] = useState(name);
    const [searchResultVisible, setSearchResultVisible] = useState(!_.isEmpty(name));

    // Set search text of route search name.
    useEffect(() => setSearchText(name), [name]);

    function handleSearch(searchName?: string) {
        setSearchResultVisible(true);
        addSearchTerm(searchName);
        history.replace(`/search?${qs.stringify({name: searchName})}`);
    }

    return (
        <div className="search">
            <div className="search-topbar">
                <Icon type="left" onClick={() => history.goBack()}/>
                <Search className="search-bar"
                        value={searchText}
                        onFocus={() => setSearchResultVisible(false)}
                        onChange={e => setSearchText(e.target.value)}
                        onSearch={() => handleSearch(searchText)}/>
                <span className="search-button" onClick={() => handleSearch(searchText)}>搜索</span>
            </div>
            {searchResultVisible ? <SearchResult name={name}/> :
                <SearchRecommendation name={name}
                                      onSelectText={text => handleSearch(text)}/>}
        </div>
    );
}


export default withRouter(SearchComponent);
